package work.getter;

import work.fram.JDBCConnect;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Dict {

    //类型-<值,code>
    private static Map<String, Map<String, String>> type__code_name = new HashMap<>();

    static {

        Statement statement = JDBCConnect.getStatement();

        Map<String, Integer> type_id = new HashMap<>();

        try {

            ResultSet resultSet = statement.executeQuery("SELECT name,id FROM sys_dict WHERE pid=0");

            //查出所有类型
            while (resultSet.next()) {
                String name = resultSet.getString("name");
                int id = resultSet.getInt("id");
                type_id.put(name, id);
            }

            //找到类型对应的子节点

            type_id.forEach((type,id)->{

                try {
                    ResultSet query = statement.executeQuery("SELECT name,code FROM sys_dict WHERE pid=" + id);

                    Map<String, String> map = new HashMap<>();
                    while (query.next()) {
                        String name = query.getString("name");
                        String code = query.getString("code");
                        map.put(name, code);
                    }

                    type__code_name.put(type, map);

                } catch (SQLException e) {
                    e.printStackTrace();
                }

            });


        } catch (SQLException e) {
            e.printStackTrace();
        }


        Map<String, String> gender = new HashMap<>();

        gender.put("男", "0");
        gender.put("女", "1");

        type__code_name.put("性别", gender);

    }


    public static Map<String, String> getByType(String type) {
        return type__code_name.get(type);
    }

    public static Map<String, Map<String, String>> getAll() {
        return type__code_name;
    }
    public static Set<String> getTypeSet() {
        return type__code_name.keySet();
    }


    public static String mapValueToCode(String type, String value) {
        Map<String, String> byType = getByType(type);
        if (byType == null) {
            return null;
        }
        return byType.get(value);
    }

}
